using System;
using System.Web;
using System.Web.Caching;
using Source.Common;
using Source.ServiceLayer;

namespace Source.ServiceLayer
{
    public interface ISessionTokenCache
    {
        void StoreWithDefaultTimeOut(Guid token, IUser user);
        bool IsTokenForUserCorrect(Guid token, IUser user);
    }

    public class SessionTokenCache : ISessionTokenCache
    {
        private readonly IConfigurationProvider configurationProvider;

        public SessionTokenCache(IConfigurationProvider configurationProvider)
        {
            this.configurationProvider = configurationProvider;
        }

        public void StoreWithDefaultTimeOut(Guid token, IUser user)
        {
            HttpRuntime.Cache.Insert(token.ToString(), user, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(configurationProvider.SessionTokenCacheTTLInMinutes));
        }

        public bool IsTokenForUserCorrect(Guid token, IUser user)
        {
            var cachedUserForToken = HttpRuntime.Cache.Get(token.ToString()) as IUser;

            if (cachedUserForToken == null)
            {
                return false;
            }

            return cachedUserForToken.UserId == user.UserId;
        }
    }
}